Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Usar "leer" para establecer variables

En bash desde la CLI puedo hacer:

 $ ERR_TYPE=$"OVERLOAD" $ echo $ERR_TYPE OVERLOAD $ read ${ERR_TYPE}_ERROR 1234 $ echo $OVERLOAD_ERROR 1234

Esto funciona muy bien para establecer mi nombre de variable dinámicamente; en un script no funciona. Lo intenté:

 #!/bin/env bash ERR_TYPE=("${ERR_TYPE[@]}" "OVERLOAD" "PANIC" "FATAL") for i in "${ERR_TYPE[@]}" do sh -c $(echo ${i}_ERROR=$"1234") done echo $OVERLOAD_ERROR # output is blank # I also tried these: # ${i}_ERROR=$(echo ${i}_ERROR=$"1234") # command not found # read ${i}_ERROR=$(echo ${i}_ERROR=$"1234") # it never terminates

¿Cómo configuraría una variable como lo hago desde CLI, pero en un script? Gracias

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Cuando usa nombres de variables dinámicas en lugar de matrices asociativas, realmente necesita cuestionar su enfoque.

 err_type=("OVERLOAD" "PANIC" "FATAL") declare -A error for type in "${err_type[@]}"; do error[$type]=1234 done

Sin embargo, en bash usarías declare :

 declare "${i}_error=1234"

Su enfoque falla porque genera un nuevo shell, pasa el comando OVERLOAD_ERROR=1234 y luego sale del shell. Su shell actual no se ve afectado en absoluto.

Quítese el hábito de usar ALLCAPSVARNAMES. Un día escribirá PATH=... y luego se preguntará por qué su script no funciona.

over 4 years ago · Santiago Trujillo Report

0

Yo usaría eval . Sin embargo, creo que esto se consideraría una mala práctica (tenía algo que ver con el hecho de que eval es "malvado" porque permite una mala entrada o algo así):

 eval "${i}_ERROR=1234"
over 4 years ago · Santiago Trujillo Report

0

Si la variable contendrá un número, puede usar let .

 #!/bin/bash ERR_TYPE=("OVERLOAD" "PANIC" "FATAL") j=0 for i in "${ERR_TYPE[@]}" do let ${i}_ERROR=1000+j++ done echo $OVERLOAD_ERROR echo $PANIC_ERROR echo $FATAL_ERROR

Esto da como resultado:

 1000 1001 1002
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!